from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from acdmpage.models import academy_page,paper,award,project,service,record,intro
from user.models import User
from note.views import check_session_cookies

def check_session_cookies(request):
    username=request.session.get('username')
    if not username:
        username=request.COOKIES.get('username')
        if not username:
            return False
        is_exist=User.objects.filter(username=username)
        if is_exist:
            request.session['username']=username
            request.session['uid'] = request.COOKIES.get('uid')
            return True
        else:
            return False
    else:
        is_exist = User.objects.filter(username=username)
        if is_exist:
            return True
        else:
            username = request.COOKIES.get('username')
            if not username:
                return False
            is_exist = User.objects.filter(username=username)
            if is_exist:
                request.session['username'] = username
                request.session['uid'] = request.COOKIES.get('uid')
                return True
            else:
                return False

def check_login(fn):
    def wrap(request, *args,**kwargs):
        if check_session_cookies(request):
            return fn(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/user/login')
    return wrap

# Create your views here.
@check_login
def acdmpage_view(request):
    if request.method=="GET":
        name=request.session.get('username')
        search_name=name
        intros=[]
        papers = []
        projects=[]
        awards=[]
        services=[]
        records=[]
        for v in intro.objects.filter(user_id=name):
            intros.append(v)
        for v in paper.objects.filter(user_id=name):
            papers.append(v)
        for v in project.objects.filter(user_id=name):
            projects.append(v)
        for v in award.objects.filter(user_id=name):
            awards.append(v)
        for v in service.objects.filter(user_id=name):
            services.append(v)
        for v in record.objects.filter(user_id=name):
            records.append(v)
        page=academy_page.objects.get(user_id=name)

        return render(request,'acdmpage/acdmpage.html',locals())
    elif request.method=="POST":
        name = request.session['username']
        search_name = name
        try:
            intro.objects.filter(user_id=name).all().delete()
            paper.objects.filter(user_id=name).all().delete()
            project.objects.filter(user_id=name).all().delete()
            award.objects.filter(user_id=name).all().delete()
            service.objects.filter(user_id=name).all().delete()
            record.objects.filter(user_id=name).all().delete()
            user = academy_page.objects.get(user_id=name)
            file_obj=request.FILES.get('img_head')
            if file_obj:
                file_name = './static/img/' + name + '_head' + '.' + file_obj.name.split('.')[-1]
                user.pic = file_name[1:]
                with open(file_name, 'wb+') as f:
                    f.write(file_obj.read())

            user.name = str(request.POST['name'])
            user.email_link = str(request.POST['email_link'])
            user.major = str(request.POST['major'])
            user.phone_link = str(request.POST['phone_link'])
            user.zhihu_link = str(request.POST['zhihu_link'])
            user.blog_link = str(request.POST['blog_link'])
            user.github_link = str(request.POST['github_link'])
            user.introduction = str(request.POST['profile'])
            user.save()

            for label in ["intro","proj","paper","award","service","record"]:
                num=int(request.POST[label+"_num"])
                for i in range(num):
                    if label=="intro":
                        user.intro_num = num
                        op=intro.objects.create(user_id=name)
                    elif label=="paper":
                        user.paper_num = num
                        op=paper.objects.create(user_id=name)
                    elif label=="proj":
                        user.project_num = num
                        op=project.objects.create(user_id=name)
                    elif label=="award":
                        user.award_num = num
                        op=award.objects.create(user_id=name)
                    elif label=="service":
                        user.service_num = num
                        op=service.objects.create(user_id=name)
                    elif label=="record":
                        user.record_num = num
                        op=record.objects.create(user_id=name)

                    op.description=str(request.POST[label+"_"+str(i+1)])
                    if label!="intro":
                        op.time=str(request.POST[label + "_time_" + str(i + 1)])
                        op.title=str(request.POST[label + "_title_" + str(i + 1)])
                        if label != "record":
                            op.link=str(request.POST[label + "_link_" + str(i + 1)])
                            if label != "service":
                                op.auther_list = str(request.POST[label + "_people_" + str(i + 1)])
                    op.save()
                print("保存成功")
            return HttpResponseRedirect('mysite')
        except Exception as e:
            print(name,e)
            return HttpResponseRedirect('../index')

def test_view(request,name=None):
    return render(request,'acdmpage/test.html',locals())

def ones_view(request,search_name=None):
    if request.method=="GET":
        is_ok=academy_page.objects.filter(user_id=search_name)
        if is_ok:
            name=request.session.get('username')
            intros=[]
            papers = []
            projects=[]
            awards=[]
            services=[]
            records=[]
            for v in intro.objects.filter(user_id=search_name):
                intros.append(v)
            for v in paper.objects.filter(user_id=search_name):
                papers.append(v)
            for v in project.objects.filter(user_id=search_name):
                projects.append(v)
            for v in award.objects.filter(user_id=search_name):
                awards.append(v)
            for v in service.objects.filter(user_id=search_name):
                services.append(v)
            for v in record.objects.filter(user_id=search_name):
                records.append(v)
            page=academy_page.objects.get(user_id=search_name)
            print(page.name,page.major,page.zhihu_link,page.github_link)
            return render(request,'acdmpage/acdmpage.html',locals())
    return HttpResponseRedirect('../index')